package com.lumlord.util;

import com.alibaba.nacos.client.utils.StringUtils;
import com.google.gson.*;

public class GsonTools {
    private static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();

    public static String toJson(Object src) {
        return gson.toJson(src);
    }

    public static <T> T fromJson(JsonObject jsonObject, Class<T> clazz) {
        return gson.fromJson(jsonObject, clazz);
    }

    public static <T> T fromJson(JsonElement json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    public static <T> T jsonToObject(String jsonBody, Class<T> clazz) {
        JsonObject jsonObject = toJsonObject(jsonBody);
        return fromJson(jsonObject, clazz);
    }

    public static JsonObject toJsonObject(String jsonBody) {
        if (null == jsonBody || jsonBody.trim().length() == 0) {
            return null;
        }

        JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonBody);
        return  jsonObject;
    }

    public static Boolean isJsonString(String str) {
        if (StringUtils.isNotBlank(str)) {
            str = str.trim();
            if (str.startsWith("{") && str.endsWith("}")) {
                return true;
            } else if (str.startsWith("[") && str.endsWith("]")) {
                return true;
            }
        }
        return false;
    }
}
